package cn.zhejianglao.oss.exception;

import cn.zhejianglao.oss.common.Response;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;

@ControllerAdvice
@Slf4j
public class GlobalExceptionHandler {
    @ExceptionHandler(value = RuntimeException.class)
    @ResponseBody
    public Response runtimeExceptionHandler(RuntimeException exception) {
        log.error("system runtime exception", exception);
        return Response.fail("发生错误: " + exception.getMessage());
    }

    @ExceptionHandler(value = Exception.class)
    @ResponseBody
    public Response exceptionHandler(HttpServletRequest request, Exception exception) {
        log.error("system exception", exception);
        if (exception.getCause() instanceof HttpRequestMethodNotSupportedException) {
            return Response.fail("接口不存在");
        }else{
            return Response.fail("发生错误: " + exception.getMessage());
        }
    }
}
